// message.js
import { render, h } from 'vue'
import messageComponent from './MessageBox.vue'
interface MessageBoxOptions {
  type?: 'info' | 'success' | 'warning' | 'error'
  message: string
  duration?: number
  showClose?: boolean
}
const boxList: any[] = []
const MessageBox = (
  options = {
    type: 'success',
    message: '',
    duration: 3000,
    showClose: true
  } as MessageBoxOptions
) => {
  const box = document.createElement('div')
  const refresh = () => {
    boxList.forEach((item, index) => {
      item.firstElementChild.style.top = `${index * 80 + 30}px`
    })
  }

  // 先从列表中删除，让出占位空间
  const close = () => {
    const index = boxList.indexOf(box)
    if (index !== -1) {
      boxList.splice(index, 1)
    }
    refresh()
  }
  // 过渡动画播放完之后 从 body 上移除组件dom
  const handleDestroy = () => {
    document.body.removeChild(box)
    close()
  } // 使用 h 函数创建 vnode
  const vnode = h(messageComponent, {
    message: options.message,
    duration: options.duration,
    destroy: handleDestroy,
    close
  })
  // 使用 render 函数将 vnode 渲染为真实DOM并挂载到 body 上
  render(vnode, box)
  boxList.push(box)
  refresh()
  document.body.appendChild(box)
}

MessageBox.info = (message: string, duration?: number) => {
  MessageBox({
    type: 'info',
    message,
    duration
  })
}
MessageBox.warning = (message: string, duration?: number) => {
  MessageBox({
    type: 'warning',
    message,
    duration
  })
}
MessageBox.success = (message: string, duration?: number) => {
  MessageBox({
    type: 'success',
    message,
    duration
  })
}
MessageBox.error = (message: string, duration?: number) => {
  MessageBox({
    type: 'error',
    message,
    duration
  })
}

export default MessageBox
